package servlet.huwenyao;

import net.sf.json.JSONObject;
import org.apache.poi.util.StringUtil;
import pojo.Order;
import service.OrderService;
import service.impl.OrderServiceImpl;
import util.ExcelUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(value = "/ImportServlet")
public class ImportServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //定义标识符
        request.setCharacterEncoding("UTF-8");
        String path = "C:\\Users\\Administrator\\Desktop\\" + request.getParameter("file");
        //调用读取excel的方法，并得到一个返回值集合
        List<String> list = ExcelUtil.readByFilePath(path);
        if (list == null) {
            JSONObject json=new JSONObject();
            json.put("msg","操作失败!");
            PrintWriter out = response.getWriter();
            out.print(json);
            return;
        }
        int num = 0;
        //创建service对象
        OrderService cs = new OrderServiceImpl();
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //循环遍历集合，并得到字符串，然后切割字符串，获得分类类型
        for (int i = 1; i < list.size(); i++) {
            Order c = new Order();
            String[] ss = list.get(i).split("`");
            if(ss[3]=="已完成"){
                 ss[3]="0";
            }else if(ss[3]=="待付款"){
                ss[3]="1";
            }
            else if(ss[3]=="待发货"){
                ss[3]="2";
            }
            else if(ss[3]=="待收货"){
                ss[3]="3";
            }
            else if(ss[3]=="待评论"){
                ss[3]="4";
            }
            //通过set方法，向对象里写入属性
            c.setConsumerId(cs.userName(ss[0]).getuID());
            c.setWareId(ss[1]);
            c.setOrderPrice(Integer.parseInt(ss[2]));
            c.setOrderState(Integer.parseInt(ss[3]));
            c.setOrderRemarks(ss[4]);
            c.setOrderAddress(ss[5]);
            try {
                c.setOrderDate(formatDate.parse(ss[6]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            num = cs.InseOrder(c);
            if (num > 0) {
                num++;
            }
        }
        JSONObject json=new JSONObject();
        if (num > 0) {
            json.put("msg","操作成功!");
        } else {
            json.put("msg","操作失败!");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request,response);
    }
}
